import 'package:equatable/equatable.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import '../../im/page/bloc/BaseBloc.dart';
import '../../im/pojo/Enums.dart';

final class PullRefreshCubit extends BaseBloc<PullRefreshEvent, PullRefreshState> {

  PullRefreshCubit() : super(PullRefreshState.loading()) {
    on<PullRefreshInitEvent>((event, emit) {
      _init(state);
    });
    on<PullRefreshLoadNewsEvent>((event, emit) {
      _loadNews(state, event.refreshController);
    });
    on<PullRefreshLoadOldsEvent>((event, emit) {
      _loadOlds(state, event.refreshController);
    });
  }

  _init(PullRefreshState oldState) {
    var dataList = <String>[];
    for (var i=1; i<11; i++) {
      var d = 0 + i;
      dataList.add(d.toString());
    }
    var nextIndex = 0 + 10;
    emit(oldState.copy(nextIndex: nextIndex, preIndex: 10, dataList: dataList, state: LoadingState.success));
  }

  _loadNews(PullRefreshState oldState, RefreshController refreshController) {
    var dataList = List.of(oldState.dataList);
    for (var i=1; i<11; i++) {
      var d = oldState.nextIndex + i;
      dataList.add(d.toString());
    }
    var nextIndex = oldState.nextIndex + 10;
    emit(oldState.copy(nextIndex: nextIndex, dataList: dataList));
    refreshController.loadComplete();
  }

  _loadOlds(PullRefreshState oldState, RefreshController refreshController) {
    var dataList = List.of(oldState.dataList);
    for (var i=1; i<11; i++) {
      var d = oldState.preIndex - i;
      dataList.insert(0, d.toString());
    }
    var nextIndex = oldState.preIndex - 10;
    emit(oldState.copy(preIndex: nextIndex, dataList: dataList));
    refreshController.refreshCompleted();
  }
}

final class PullRefreshState extends Equatable {

  final LoadingState state;
  final int preIndex;
  final int nextIndex;
  final List<String> dataList;

  const PullRefreshState._({
    this.state = LoadingState.loading,
    this.preIndex = 1000,
    this.nextIndex = 1000,
    this.dataList = const <String>[],
  });

  PullRefreshState copy({int? preIndex, int? nextIndex, List<String>? dataList, LoadingState? state}) {
    return PullRefreshState._(
      preIndex: preIndex ?? this.preIndex,
      nextIndex: nextIndex ?? this.nextIndex,
      state: state ?? this.state,
      dataList: dataList ?? this.dataList,
    );
  }

  const PullRefreshState.loading() : this._();

  @override
  List<Object?> get props => [state, dataList];

}

class PullRefreshEvent {}
class PullRefreshInitEvent extends PullRefreshEvent {}
class PullRefreshLoadNewsEvent extends PullRefreshEvent {
  final RefreshController refreshController;
  PullRefreshLoadNewsEvent(this.refreshController);
}
class PullRefreshLoadOldsEvent extends PullRefreshEvent {
  final RefreshController refreshController;
  PullRefreshLoadOldsEvent(this.refreshController);
}